package com.css.fxfzaqbz.util;


import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import javax.annotation.Resource;
import javax.xml.ws.Response;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Component
public class DownloadsFile {



    @Value("${image.localDir}")
    private String localDir;

    @Resource
    private AttachmentInfoService attachmentInfoService;


    private static int count = 0;
    /**
     * 从Url中下载文件
     *
     * @param urlStr url的路径
     */
    public RestResponse downloadByUrl(String urlStr, String savePath) {

        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置部分请求头信息，根据自己的实际需要来书写，不需要的也可以删掉
            conn.setRequestProperty("api_token", "Bearer_");
            conn.setRequestProperty("Cookie", "XXL_JOB_LOGIN_IDENTITY=");
            conn.connect();
            //得到输入流
            InputStream inputStream = conn.getInputStream();
//            long startTime = System.currentTimeMillis();
//            try {
//                inputStream = conn.getInputStream();
//            } catch (IOException e) {
//                int a=conn.getResponseCode();
//                while (a==400){
//                    conn = (HttpURLConnection) url.openConnection();
//                    a = conn.getResponseCode();
//                    long endTime = System.currentTimeMillis();
//                    if (endTime-startTime>30000){
//                        return RestResponse.fail("请求超时");
//                    }
//                }
//                inputStream = conn.getInputStream();
//            }
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) { // 没有就创建该文件
                new File(savePath).mkdirs();
            }

            //获取文件名及后缀
            String headerField = conn.getHeaderField("Content-Disposition");
            String[] split = headerField.split("=");
            String fileName = URLDecoder.decode(split[1], "utf-8");
            //开始写入
            File file = new File(savePath,fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            fos.close();
            inputStream.close();
            System.out.println("the file: " + url + " download success");


            File filee = new File(savePath + File.separator + fileName);
            InputStream inputStream1 = new FileInputStream(filee);
            MultipartFile multipartFile = new MockMultipartFile(fileName, inputStream1);
            String imageFileId = getImageFileId(multipartFile,fileName);

            return RestResponse.succeed(imageFileId);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }

    }



    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[4 * 1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }




    public static byte[] readInputStream1(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }

        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }
    private  String getImageFileId(MultipartFile image,String fileName)throws IOException {
        //获取文件名称
//        String fileName=image.getOriginalFilename();
        //获取文件上传的本地路径
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        //构建文件
        assert fileName != null;
        //上传文件
        String realFileName = uploadFile(fileName,savePath,image);
        //构建实体类
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(fileName,dateDir,realFileName);
        List<AttachmentInfoEntity> list=new ArrayList<>();
        list.add(attachmentInfoEntity);
        attachmentInfoService.save(list);
        return attachmentInfoEntity.getAttachId();
    }

    private  AttachmentInfoEntity buildAttachment(String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(StringUtils.buildPrimaryId());
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath(dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }

    private static String uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_" + System.currentTimeMillis() + fileType;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, realFileName);
        multipartFile.transferTo(file);
        return realFileName;
    }

}